import React, { useState } from 'react';
import CommonLayout from '../../../components/shop/common-layout';
import { Input, Container, Row, Form, Label, Col } from 'reactstrap';
import { signUpApi, getEmailVerifyApi } from '../../../api/api';
import { toast } from "react-toastify";
import { useRouter } from 'next/router';

const Register = () => {
    const secondsRemaining = 60;
    const router = useRouter();
    const [formData, setFormData] = useState({
        fname: "",
        lname: "",
        email: "",
        password: "",
        confirmPassword: "",
        dAdress: "",
        verifyCode: "",
        zipCode: "",
        phone: ""
    });

    const [verifyCodeBtn, setVerifyCodeBtn] = useState("Send Code");
    const [countDown, setCountDown] = useState(60);
    const [codeSended, setCodeSended] = useState(false);
    const [loading, setLoading] = useState(false);

    // 处理表单输入变化  
    const handleInputChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    // 发送邮箱验证码
    const VerifyBtnOnclick = () => {
        if (!codeSended && formData.email !== "") {
            var input = { emailAdress: formData.email };
            getEmailVerifyApi(input).then(res => {
                if (res.error_code == "2000") {
                    toast.success(res.msg);
                    setVerifyCodeBtn("Resend");
                    UpdateCountDown(secondsRemaining);
                    setCodeSended(true);
                }
                else {
                    toast.warning(res.msg);
                }
            });
        }
        else if (formData.email == "") {
            toast.warning("Please Enter Your Email.");
        }
    }

    const UpdateCountDown = (secondsRemaining) => {
        // 显示倒数到控制台或页面上的元素
        // 如果倒数未完成则继续倒数
        if (secondsRemaining > 0) {
            // 递归调用updateCountdown，每隔1000毫秒（即1秒）递减一次
            setTimeout(UpdateCountDown, 1000, secondsRemaining - 1);
            setCountDown(secondsRemaining - 1);
        }
        else {
            setVerifyCodeBtn("Send Code");
            setCountDown(60);
            setCodeSended(false);
        }
    }

    const registerOnclick = () => {
        if (formData.email && formData.dAdress && formData.password && formData.confirmPassword) {
            setLoading(true);
            signUpApi(formData).then(res => {
                if (res.error_code == "2000") {
                    toast.success("Sign Up Succeed.")
                    setLoading(false);
                    router.push("/page/account/login");
                }
                else {
                    setLoading(false);
                    toast.warning(res.msg);
                }
            })
        } else {
            toast.warning("Email, Delivery Adress, PassWord are required.");
        }
    }

    return (
        <CommonLayout parent="home" title="register">
            <section className="register-page section-b-space">
                <Container>
                    <Row>
                        <Col lg="12">
                            <h3>create account</h3>
                            <div className="theme-card">
                                <Form className="theme-form">
                                    <Row>
                                        <Col md="6">
                                            <Label for="email"><span style={{ color: "red" }}>*</span>Email</Label>
                                            <Input type="text" className="form-control" id="email" name="email" placeholder="Email" required={true} onChange={handleInputChange} invalid={(formData.email == "")} />
                                        </Col>
                                        <Col md="6">
                                            <Label for="adress"><span style={{ color: "red" }}>*</span>Delivery Adress</Label>
                                            <Input type="text" className="form-control" id="dAdress" name="dAdress" placeholder="Delivery Adress" required={true} onChange={handleInputChange} invalid={(formData.dAdress == "")} />
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col md="3">
                                            <Label for="zipCode"><span style={{ color: "red" }}>*</span>Zip Code</Label>
                                            <Input type="text" className="form-control" id="zipCode" name="zipCode" placeholder="zip code" required={true} onChange={handleInputChange} invalid={(formData.zipCode == "")} />
                                        </Col>
                                        <Col md="3">
                                            <Label for="pwd"><span style={{ color: "red" }}>*</span>Phone Number</Label>
                                            <Input type="text" className="form-control" id="phone" name="phone"
                                                placeholder="Enter your phone number" required={true} onChange={handleInputChange} invalid={(formData.phone == "")} />
                                        </Col>
                                        <Col md="3">
                                            <Label for="pwd"><span style={{ color: "red" }}>*</span>Password</Label>
                                            <Input type="password" className="form-control" id="review" name="password"
                                                placeholder="Enter 8 to 18 digit numbers or letters" required={true} onChange={handleInputChange} invalid={(formData.password == "" || formData.password.length < 8 || formData.password.length > 18)} />
                                        </Col>
                                        <Col md="3">
                                            <Label for="repwd"><span style={{ color: "red" }}>*</span>Confirm Password</Label>
                                            <Input type="password" className="form-control" id="review" name="confirmPassword"
                                                placeholder="Confirm your password" required={true} onChange={handleInputChange} invalid={(formData.confirmPassword == "" || formData.confirmPassword.length < 8 || formData.confirmPassword.length > 18)} />
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col md="6">
                                            <Label for="firstName">First Name</Label>
                                            <Input type="text" className="form-control" id="fname" name="fname" placeholder="First Name"
                                                required="" onChange={handleInputChange} />
                                        </Col>
                                        <Col md="6">
                                            <Label for="lastName">Last Name</Label>
                                            <Input type="text" className="form-control" id="lname" name="lname" placeholder="Last Name"
                                                required="" onChange={handleInputChange} />
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col md="6">
                                            <Label for="verifyCode">Verify Code</Label>
                                            <div style={{ display: 'flex' }}>
                                                <Input type="text" className="form-control" id="verifyCode" name="verifyCode" placeholder="Verify Code"
                                                    required="" style={{ width: 250 }} onChange={handleInputChange} />
                                                <button type="button" onClick={VerifyBtnOnclick} className="btn-blank" style={{ height: 45, marginLeft: 20, color: codeSended ? 'gray' : 'black', cursor: codeSended ? 'default' : 'cursor' }}>{verifyCodeBtn} {codeSended && countDown}</button>
                                            </div>
                                        </Col>
                                        <Col md="6">
                                            <div style={{ position: 'absolute', right: 20 }}>
                                                <button  type="button" disabled={loading} onClick={registerOnclick} className="btn btn-solid" style={{ marginTop: 22 }}>Create Account</button>
                                            </div>
                                        </Col>
                                    </Row>
                                </Form>
                            </div>
                        </Col>
                    </Row>
                </Container>
            </section>
        </CommonLayout>
    )
}

export default Register